package com.jmuok.web.fff.web.ui;

import java.util.Collections;
import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Transactional;

import com.jmuok.web.fff.domain.User;
import com.jmuok.web.fff.web.vaadin.EntityEditor;
import com.vaadin.addon.jpacontainer.JPAContainer;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.terminal.gwt.server.WebBrowser;
import com.vaadin.ui.Table;

@Configurable
public class UserRegView extends UserView {
	private static Logger logger = Logger.getLogger(UserRegView.class);
	private static final long serialVersionUID = -5681588573383445862L;

	// private UserRegForm form;

	public static PasswordEncoder passwordEncoder = new ShaPasswordEncoder(256);

	@Autowired
	public SaltSource saltSource;

	@Override
	public EntityEditor createForm() {
		UserRegForm form = new UserRegForm();
		return form;
	}

	public UserRegForm getUserRegForm() {
		return (UserRegForm) getForm();
	}

	@Override
	protected void addListeners() {
		// clear all listeners.
	}

	@Override
	public void configureTable(Table table) {
		// do nothing.
	}

	@Transactional
	public boolean doCommit() {
		try {
			getForm().commit();
			User user = getEntityForItem(getForm().getItemDataSource());
			logger.info(user.getUserName() + " is registing...");
			if (logger.isDebugEnabled()) {
				logger.debug("Email: " + user.getEmail());
				// logger.debug("Role" + user.getRoleId());
			}

			//encode pass
			UserDetails ud = new org.springframework.security.core.userdetails.User(
					user.getUserName(), user.getPassword(),Collections.EMPTY_LIST );
			String pass = passwordEncoder.encodePassword(user.getPassword(),
					saltSource.getSalt(ud));
			user.setPassword(pass);
			
			String ip = ((WebBrowser) getForm().getApplication()
					.getMainWindow().getTerminal()).getAddress();
			logger.info("Ip:" + ip);
			user.setIp(ip);

			user.setMoney(0D);
			user.setBonus(0L);

			user.setRegAt(new Date());
			user.setAccountExpired(false);
			user.setCredentialsExpired(false);
			user.setMailReminderOn(false);
			user.setAccountLocked(false);
			// TODO email validate
			user.setAccountEnabled(true);

			// if (!getTableContainer().containsId(getIdForEntity(user))) {
			((JPAContainer<User>) getTableContainer()).addEntity(user);
			// }
			logger.info(user.getUserName() + " registed.");
			return true;
		} catch (InvalidValueException e) {
			logger.warn("regist failed.");
			// show validation error also on the save button
			getForm().setCommitErrorMessage(e.getMessage());
			return false;
		}
	}

	@Override
	public boolean isCreateAllowed() {
		return true;
	}

	@Override
	public boolean isUpdateAllowed() {
		return false;
	}

	@Override
	public boolean isDeleteAllowed() {
		return false;
	}

	@Override
	public boolean isNewEntity(User entity) {
		return true;
	}

	@Override
	public void deleteEntity(User entity) {
		throw new UnsupportedOperationException();

	}

}
